// transform pixel buffer to imgData
export class Converter {
    constructor(rescaleSlope  = 1,
        rescaleIntercept      = 1024,
        littleEndian          = true) {
        
        // chrome cannot support [new ImageData(rows, cols)] so far,
        // so we must denote a ImageData's instance.
        this.imgData          = null;
        this.pixelBuffer      = null;
        this.ww               = -1;
        this.wc               = -1;
        this.rescaleIntercept = rescaleIntercept;
        this.rescaleSlope     = rescaleSlope;
        this.littleEndian     = littleEndian;
    }
    
    // set window width & window center to a absolute values
    setWwWc(ww, wc) {
        if (!this.imgData || !this.pixelBuffer) {
            throw new Error("please specify the imgData && pixelBuffer first!");
        }
        this.ww = ww;
        this.wc = wc;
        this.convert();
    }
    
    // we just specify a imgdata for the first use.
    setImageData(imgdata) {
        this.imgData = imgData;
    }
    
    setPixelBuffer(pixelBuffer) {
        this.pixelBuffer = pixelBuffer;
    }
    
    getImageData() {
        return this.imgData;
    }
    
    convert() {
        let data    = this.imgData.data,
            len     = data.length,
            max     = this.wc + this.ww >> 1,
            min     = max - this.ww,
            endian  = this.littleEndian,
            rs      = this.rescaleSlope,
            ri      = this.rescaleIntercept,
            view    = new DataView(this.pixelBuffer.buffer),
            npi     = Number.parseInt,
            offset  = 0;

        for (let i = 0; i < len; i += 4) {
            let value = view.getInt16(offset, endian) * rs + ri;

            // increment offset
            offset += 2;

            data[i + 3] = 255; // alpha transparent
            if (value > max) {
                data[i] = data[i + 1] = data[i + 2] = 255;
                continue;
            } else if (value < min) {
                data[i] = data[i + 1] = data[i + 2] = 0;
                continue;
            }

            let grayValue = npi((value - min) * 255 / this.ww, 10);
            data[i] = data[i + 1] = data[i + 2] = grayValue;
        }
    }
    
}
